package com.jf3q.admin.controller;

import com.jf3q.admin.service.VideoService;
import com.jf3q.common.domain.EduVideo;
import com.jf3q.common.utils.VodUtils;
import com.jf3q.common.vo.ResultVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/video")
@Tag(name = "小节模块")
public class VideoController {



    @Autowired
    VideoService videoService;
    @Autowired
    VodUtils vodUtils;

    @PostMapping("/upload")
    @Operation(summary = "上传视频到阿里云")
    public ResultVo upload( MultipartFile file){
        String vid = vodUtils.uploadVod(file);
        return ResultVo.success("上传成功",vid);

    }

    @GetMapping("/auth")
    @Operation(summary = "获取播放凭证")
    public ResultVo getAuth(String vid){
        String auth = vodUtils.getVideoPlayAuth(vid);
        return ResultVo.success(auth);

    }

    @Operation(summary = "添加小节")
    @PostMapping("/saveUpdate")
    public ResultVo saveUpdate(@RequestBody EduVideo video){
        try {
            video.setPlayCount(0L);
            video.setSize(0L);
            video.setVersion(1L);
            videoService.saveOrUpdate(video);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return ResultVo.success("",null);
    }

    @Operation(summary = "查看小节详情")
    @PostMapping("/findOne/{vId}")
    public ResultVo findOne(@PathVariable String vId){
        EduVideo video = videoService.getById(vId);
        return  ResultVo.success("",video);
    }

    @Operation(summary = "删除小节")
    @PostMapping("/delVideo/{vId}")
    @Transactional
    public ResultVo delVideo(@PathVariable String vId){
        try {
            EduVideo video = videoService.getById(vId);
            //从阿里云删除视频
            if(StringUtils.hasText(video.getVideoSourceId().trim())){
                vodUtils.del(video.getVideoSourceId());
            }
            videoService.removeById(vId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return ResultVo.success("",null);
    }

}
